package com.senditcertified.mail;

import org.json.JSONException;
import org.json.JSONObject;

import com.Utility.GetEpackge;
import com.Utility.Utility;
import com.activities.SecureActivity;
import com.activities.group.TabBaseGroupActivity;
import com.activities.group.TabHomeGroupActivity;
import com.senditcertified.mail.R;
import com.parser.Deliver_Beans;
import com.parser.Error_Report;
import com.parser.Parser_Soap;
import com.soap.call.Http_Soap_Call;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

public class Message_Viewer extends Activity {
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	Deliver_Beans beans;
	EditText username, your_name, your_email, accesscode;
	CheckBox hidecheckbox, checkbox;
	TextView hidetext;
	ProgressDialog pd;
	Button openchoice, btn_continue;
	String Access_Code = null;
	int id = 0;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// TODO Put your code here
		View viewToLoad = LayoutInflater.from(this.getParent()).inflate(
				R.layout.inboxmain, null);
		this.setContentView(viewToLoad);
		beans = (Deliver_Beans) this.getIntent().getExtras()
				.getSerializable("bean");
		username = (EditText) findViewById(R.id.username);
		your_name = (EditText) findViewById(R.id.your_name);
		your_email = (EditText) findViewById(R.id.your_email);
		accesscode = (EditText) findViewById(R.id.accesscode);
		hidetext = (TextView) findViewById(R.id.hidetext);

		username.setText(beans.getSender());
		your_name.setText(beans.getYourName());
		your_email.setText(beans.getYourEmail());
		accesscode.setText("");
		LinearLayout linear = (LinearLayout) findViewById(R.id.linear);
		LinearLayout linear2 = (LinearLayout) findViewById(R.id.linear2);

		hidecheckbox = (CheckBox) findViewById(R.id.hidecheckbox);
		checkbox = (CheckBox) findViewById(R.id.checkbox);

		checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					openchoice.setVisibility(View.VISIBLE);
				} else {
					openchoice.setVisibility(View.GONE);
				}
			}
		});

		if (hidecheckbox.isChecked()) {
			hidetext.setVisibility(View.VISIBLE);
		} else {
			hidetext.setVisibility(View.GONE);
		}

		hidecheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					hidetext.setVisibility(View.VISIBLE);
				} else {
					hidetext.setVisibility(View.GONE);
				}

			}
		});

		openchoice = (Button) findViewById(R.id.openchoice);
		btn_continue = (Button) findViewById(R.id.login_btn);

		openchoice.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Access_Code = accesscode.getText().toString();
				id = 1;
				/*
				 * if (Access_Code == null || Access_Code.length() == 0 &&
				 * beans.isPending_Accepted()) { AlertDialog.Builder builder =
				 * new AlertDialog.Builder( getParent());
				 * builder.setMessage("Please enter access code?")
				 * .setCancelable(false) .setPositiveButton("OK", new
				 * DialogInterface.OnClickListener() { public void onClick(
				 * DialogInterface dialog, int id) { dialog.dismiss(); // new //
				 * User_Token_Expire().execute(""); } });
				 * 
				 * AlertDialog alertDialog = builder.create();
				 * alertDialog.show();
				 * 
				 * } else
				 */
				new GetEPackageError().execute(Utility.getStringPreference(
						getParent(), "LoginToken", ""), beans.getMsg_UID(),
						Access_Code);

			}
		});

		btn_continue.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				id = 2;
				Access_Code = accesscode.getText().toString();
				new GetDeliveryAcceptance().execute(Utility
						.getStringPreference(getParent(), "LoginToken", ""),
						beans.getMsg_UID());

				/*
				 * if (Access_Code == null || Access_Code.length() == 0 &&
				 * beans.isPending_Accepted()) { AlertDialog.Builder builder =
				 * new AlertDialog.Builder( getParent());
				 * builder.setMessage("Please enter access code?")
				 * .setCancelable(false) .setPositiveButton("OK", new
				 * DialogInterface.OnClickListener() { public void onClick(
				 * DialogInterface dialog, int id) { dialog.dismiss(); // new //
				 * User_Token_Expire().execute(""); } });
				 * 
				 * AlertDialog alertDialog = builder.create();
				 * alertDialog.show();
				 * 
				 * } else {
				 * 
				 * 
				 * 
				 * 
				 * new GetEPackageError().execute(Utility.getStringPreference(
				 * getParent(), "LoginToken", ""), beans.getMsg_UID(),
				 * Access_Code);
				 * 
				 * }
				 */
			}
		});
		System.out.println("y" + beans.isPending_Accepted());
		if (!beans.isPending_Accepted()) {
			linear.setVisibility(View.GONE);
			// linear2.setVisibility(View.GONE);
			btn_continue.setVisibility(View.GONE);

		}

		try {
			((TabHomeGroupActivity) ((TabBaseGroupActivity) getParent())
					.getParent()).registerHomeTabClick(this);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public class GetEPackageError extends AsyncTask<String, Void, Boolean> {
		boolean result = false;
		// String error_msg = "";
		String Result = null;
		Parser_Soap parse = new Parser_Soap();
		Error_Report repor = new Error_Report();

		protected Boolean doInBackground(String... params) {
			Http_Soap_Call call = Http_Soap_Call.create_connection("",
					getParent());
			if (call != null) {
				// Result = parse.GetLoginToken(
				// call.GetLoginToken(Username, params[0], repor), repor);
				Result = parse.GetEPackageError(call.GetEPackageError(
						params[0], params[1], params[2], repor), repor);
				if (Result != null) {
					result = true;

				} else {
					// error_msg=Utility.INVALID_USER;
					System.out.println("false");
					result = false;
					repor.setMessage("Internal Error");
				}

			} else {
				repor.setMessage(Utility.NETWORK_ISSUE);
				return false;
			}

			return result;
		}

		protected void onPreExecute() {
			pd = ProgressDialog.show(getParent(), null,
					getString(R.string.loader));
		}

		protected void onPostExecute(Boolean result) {
			// This method runs in the UI thread

			pd.dismiss();
			if (result) {
				// Utility.printLog("Login Responce", "Login successfully");
				// Utility.setStringPreference(getParent(), "LoginToken",
				// Result);
				try {
					JSONObject js = new JSONObject(Result);
					String Result = js.getString("ReturnValue");

					if (TextUtils.isEmpty(Result)) {

						new GetEPackage().execute(Utility.getStringPreference(
								getParent(), "LoginToken", ""), beans
								.getMsg_UID(), Access_Code);

						/*
						 * new GetDeliveryAcceptance().execute(Utility
						 * .getStringPreference(getParent(), "LoginToken", ""),
						 * beans .getMsg_UID());
						 */

					} else {
						AlertDialog.Builder builder = new AlertDialog.Builder(
								getParent());
						builder.setMessage(Result)
								.setCancelable(false)
								.setPositiveButton("OK",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												dialog.dismiss();

											}
										});

						AlertDialog alertDialog = builder.create();
						alertDialog.show();

					}

					/*
					 * AlertDialog.Builder builder = new
					 * AlertDialog.Builder(getParent());
					 * builder.setMessage(Result) .setCancelable(false)
					 * .setPositiveButton("Ok", new
					 * DialogInterface.OnClickListener() { public void onClick(
					 * DialogInterface dialog, int id) { dialog.dismiss(); } });
					 * 
					 * AlertDialog alertDialog = builder.create();
					 * alertDialog.show();
					 */
				} catch (Exception e) {
					// TODO: handle exception
				}

			} else {
				// Utility.printLog("Login Responce", "Login Unsuccessfully");
				// Toast.makeText(Password.this, repor.getMessage(),
				// Toast.LENGTH_SHORT).show();
			}

		}
	}

	public class GetEPackage extends AsyncTask<String, Void, Boolean> {
		boolean result = false;
		// String error_msg = "";
		String Result = null;
		Parser_Soap parse = new Parser_Soap();
		Error_Report repor = new Error_Report();

		protected Boolean doInBackground(String... params) {
			Http_Soap_Call call = Http_Soap_Call.create_connection("",
					getParent());
			if (call != null) {
				// Result = parse.GetLoginToken(
				// call.GetLoginToken(Username, params[0], repor), repor);
				Result = parse.GetEPackage(call.GetEPackage(params[0],
						params[1], params[2], repor), repor);
				if (Result != null) {
					result = true;

				} else {
					// error_msg=Utility.INVALID_USER;
					System.out.println("false");
					result = false;
					repor.setMessage("Internal Error");
				}

			} else {
				repor.setMessage(Utility.NETWORK_ISSUE);
				return false;
			}

			return result;
		}

		protected void onPreExecute() {
			pd = ProgressDialog.show(getParent(), null,
					getString(R.string.loader));
		}

		protected void onPostExecute(Boolean result) {
			// This method runs in the UI thread

			pd.dismiss();
			if (result) {
				// Utility.printLog("Login Responce", "Login successfully");
				// Utility.setStringPreference(getParent(), "LoginToken",
				// Result);
				System.out.println("Parse Result XXXXXX" + Result + "");
				parse_Delivery(Result);

			} else {
				// Utility.printLog("Login Responce", "Login Unsuccessfully");
				// Toast.makeText(Password.this, repor.getMessage(),
				// Toast.LENGTH_SHORT).show();
			}

		}
	}

	public class GetDeliveryAcceptance extends AsyncTask<String, Void, Boolean> {
		boolean result = false;
		// String error_msg = "";
		String Result = null;
		Parser_Soap parse = new Parser_Soap();
		Error_Report repor = new Error_Report();

		protected Boolean doInBackground(String... params) {
			Http_Soap_Call call = Http_Soap_Call.create_connection("",
					getParent());
			if (call != null) {
				// Result = parse.GetLoginToken(
				// call.GetLoginToken(Username, params[0], repor), repor);
				Result = parse.RequestAccessCode(
						call.RequestAccessCode(params[0], params[1], repor),
						repor);
				if (Result != null) {
					result = true;

				} else {
					// error_msg=Utility.INVALID_USER;
					System.out.println("false");
					result = false;
					repor.setMessage("Internal Error");
				}

			} else {
				repor.setMessage(Utility.NETWORK_ISSUE);
				return false;
			}

			return result;
		}

		protected void onPreExecute() {
			pd = ProgressDialog.show(getParent(), null,
					getString(R.string.loader));
		}

		protected void onPostExecute(Boolean result) {
			// This method runs in the UI thread

			pd.dismiss();
			if (result) {
				// Utility.printLog("Login Responce", "Login successfully");
				// Utility.setStringPreference(getParent(), "LoginToken",
				// Result);
				System.out.println("Parse Result");

				try {
					JSONObject jobj = new JSONObject(Result);

					AlertDialog.Builder builder = new AlertDialog.Builder(
							getParent());
					builder.setMessage(jobj.getString("ReturnValue"))
							.setCancelable(false)
							.setPositiveButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.dismiss();

										}
									});

					AlertDialog alertDialog = builder.create();
					alertDialog.show();

				} catch (Exception e) {
					// TODO: handle exception
				}

				Access_Code = Result;
				// parse_Delivery(Result);

			} else {
				// Utility.printLog("Login Responce", "Login Unsuccessfully");
				// Toast.makeText(Password.this, repor.getMessage(),
				// Toast.LENGTH_SHORT).show();
			}

		}
	}

	public void parse_Delivery(String result) {
		try {
			// JSONArray aaray = new JSONArray(result);
			System.out.println("COME");
			GetEpackge getEpackge = null;

			// for (int i = 0; i < aaray.length(); i++) {

			JSONObject jobj = new JSONObject(result);

			getEpackge = new GetEpackge();

			getEpackge.setFile_create(jobj.getString("file_create"));
			getEpackge.setFile_desc(jobj.getString("file_desc"));
			getEpackge.setUsername(jobj.getString("username"));
			getEpackge.setFirst_name(jobj.getString("first_name"));
			getEpackge.setLast_name(jobj.getString("last_name"));

			getEpackge.setFile_msg(jobj.getString("file_msg"));

			if (jobj.has("file_name1")) {
				getEpackge.setFile_name(jobj.getString("file_name1"));
			}

			getEpackge.setFile_name2(jobj.getString("file_name2"));
			getEpackge.setFile_name3(jobj.getString("file_name3"));
			getEpackge.setFile_name4(jobj.getString("file_name4"));
			getEpackge.setFile_name5(jobj.getString("file_name5"));
			getEpackge.setFile_name6(jobj.getString("file_name6"));

			getEpackge.setFile_name7(jobj.getString("file_name7"));
			getEpackge.setFile_name8(jobj.getString("file_name8"));
			getEpackge.setFile_name9(jobj.getString("file_name9"));
			getEpackge.setFile_name10(jobj.getString("file_name10"));
			getEpackge.setVoice_msg(jobj.getString("voice_msg"));

			getEpackge.setVideo_msg(jobj.getString("video_msg"));
			getEpackge.setUser_id(jobj.getString("user_id"));
			getEpackge.setUpload_dir(jobj.getString("upload_dir"));
			getEpackge.setCollaboration(jobj.getString("collaboration"));
			getEpackge.setSend_to(jobj.getString("send_to"));
			getEpackge.setNo_download(jobj.getString("no_download"));
			getEpackge.setNo_forward(jobj.getString("no_forward"));

			getEpackge.setNo_print(jobj.getString("no_print"));
			getEpackge.setAdd_watermark(jobj.getString("add_watermark"));
			getEpackge.setAllow_view(jobj.getString("allow_view"));

			System.out.println("Hummm Na Payar karte hai aap se");

			// }
			// if (getEpackge != null) {
			Intent intent = new Intent((TabBaseGroupActivity) getParent(),
					SecureActivity.class);
			intent.putExtra("Message", getEpackge);
			intent.putExtra("MSG_ID", beans.getMsg_UID());
			((TabBaseGroupActivity) getParent()).startChildActivity(
					SecureActivity.class.getSimpleName(), intent);

			// finish();

			// } else {
			// Toast.makeText(this, "Unable to respond Epackages",
			// Toast.LENGTH_SHORT).show();
			// }

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
